package cn.edu.tju.elm.controller.handler;

import cn.edu.tju.elm.common.response.HttpResult;
import cn.edu.tju.elm.exception.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j // Lombok 注解，自动生成 Logger
@RestControllerAdvice // 组合了 @ControllerAdvice 和 @ResponseBody
public class GlobalExceptionHandler {

//    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理数据未找到异常（优先匹配具体异常）
     */
    @ExceptionHandler(DataNotFoundException.class)
    public ResponseEntity<HttpResult<?>> handleDataFormatException(DataNotFoundException e) {
        HttpResult<?> response = HttpResult.failure(e.getCode(), e.getMessage());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON); // 显式设置 JSON 类型
        return new ResponseEntity<>(response, headers, HttpStatus.NOT_FOUND);
    }

    /**
     * 处理参数校验异常（如 @Valid 校验失败）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<HttpResult<?>> handleValidationException(MethodArgumentNotValidException e) {
        // 提取校验失败的字段信息
//        String errorMsg = e.getBindingResult().getFieldErrors().stream()
//                .map(FieldError::getDefaultMessage)
//                .collect(Collectors.joining("; "));
//        HttpResult<?> response = HttpResult.failure(HttpStatus.BAD_REQUEST.value(), errorMsg);
        HttpResult<?> response = HttpResult.failure(e.getCode(), e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理权限不足异常
     */
    @ExceptionHandler(ForbiddenException.class)
    public ResponseEntity<HttpResult<?>> handleForbiddenException(ForbiddenException e) {
        HttpResult<?> response = HttpResult.failure(e.getCode(), e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
    }

    /**
     * 处理登录用户名或密码错误
     */
    @ExceptionHandler(BadCredentialsException.class)
    public ResponseEntity<HttpResult<?>> handleBadCredentialsException(BadCredentialsException e){
        HttpResult<?> response = HttpResult.failure(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
    }

    /**
     * 处理图片IO失败异常
     */
    @ExceptionHandler(ImageIOException.class)
    public ResponseEntity<HttpResult<?>> handleImageIOException(ImageIOException e){
        log.error("图片IO: {}", e.getMessage(), e);
        HttpResult<?> response = HttpResult.failure(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 处理通用业务异常（兜底业务异常）
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<HttpResult<?>> handleBusinessException(BusinessException e) {
        HttpResult<?> response = HttpResult.failure(e.getCode(), e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 数据异常
     */
    @ExceptionHandler(DataAbnormalException.class)
    public ResponseEntity<HttpResult<?>> httpDataAbnormalException(DataAbnormalException e){
        HttpResult<?> response = HttpResult.failure(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 处理系统级异常（未捕获的运行时异常）
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<HttpResult<?>> handleRuntimeException(RuntimeException e) {
        log.error("系统运行时异常: {}", e.getMessage(), e); // 记录详细日志
        HttpResult<?> response = HttpResult.failure(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                e.getMessage()
        );
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 处理所有其他异常（兜底）
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<HttpResult<?>> handleAllExceptions(Exception e) {
        log.error("未知异常: {}", e.getMessage(), e);
        HttpResult<?> response = HttpResult.failure(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                e.getMessage()
        );
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}